package com.yjh.auth.service;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.yjh.auth.entity.DetailsUser;
import com.yjh.auth.feign.RemoteUserService;
import enums.SysUser;
import constant.CommonConstants;
import constant.SecurityConstants;
import enums.UserInfo;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import util.R;

import java.util.*;

@Component
@Service
@Slf4j
@AllArgsConstructor
public class SysUserDetailsService implements UserDetailsService {

    private final RemoteUserService remoteUserService;
    private final CacheManager cacheManager;

    /**
     * 用户密码登录
     *
     * @param username 用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    @SneakyThrows
    public UserDetails loadUserByUsername(String username) {
        //读取缓存数据
        Cache cache = cacheManager.getCache("user_details");
        if (cache != null && cache.get(username) != null) {
            return (DetailsUser) cache.get(username).get();
        }
        R<UserInfo> result = remoteUserService.info(username);
        UserDetails userDetails = getUserDetails(result);
        cache.put(username, userDetails);
        return userDetails;
    }




//    @Override
//    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException{
//        SysUser  user = new SysUser();
//        user.setUsername(username);
//        SysUser sysUser = sysUserMapper.selectOne(user);
//        if (null == sysUser) {
//            throw new UsernameNotFoundException(username);
//        }
//        //设置角色列表  （ID）
//        List<Integer> roleIds = sysRoleService.listRolesByUserId(sysUser.getUserId())
//                .stream()
//                .map(SysRole::getRoleId)
//                .collect(Collectors.toList());
//
//
//        //设置权限列表（menu.permission）
//        Set<String> permissions = new HashSet<>();
//        roleIds.forEach(roleId -> {
//            List<String> permissionList = sysMenuService.listMenusByRoleId(roleId)
//                    .stream()
//                    .filter(menuVo -> StringUtils.isNotEmpty(menuVo.getPermission()))
//                    .map(MenuVO::getPermission)
//                    .collect(Collectors.toList());
//            permissions.addAll(permissionList);
//        });
//        Set<String> dbAuthsSet = new HashSet<>();
//        // 获取角色
//        roleIds.forEach(roleId -> dbAuthsSet.add(SecurityConstants.ROLE + roleId));
//        // 获取资源
//        dbAuthsSet.addAll(permissions);
//
//
//        Collection<? extends GrantedAuthority> authorities
//                = AuthorityUtils.createAuthorityList(dbAuthsSet.toArray(new String[0]));
//        boolean enabled = StrUtil.equals(sysUser.getLockFlag(), CommonConstants.STATUS_NORMAL);
//
//        return  new DetailsUser(sysUser.getUserId(), sysUser.getDeptId(), sysUser.getTenantId(),sysUser.getAvatar(), sysUser.getUsername(), SecurityConstants.BCRYPT + sysUser.getPassword(), enabled,
//                true, true, !CommonConstants.STATUS_LOCK.equals(sysUser.getLockFlag()), authorities);
//    }
    /**
     * 构建userdetails
     *
     * @param result 用户信息
     * @return
     */
    private UserDetails getUserDetails(R<UserInfo> result) {
        if (result == null || result.getData() == null) {
            log.info("UsernameNotFoundException(用户不存在)");
            throw new UsernameNotFoundException("用户不存在");
        }

        UserInfo info = result.getData();
        Set<String> dbAuthsSet = new HashSet<>();
        if (ArrayUtil.isNotEmpty(info.getRoles())) {
            // 获取角色
            Arrays.stream(info.getRoles()).forEach(roleId -> dbAuthsSet.add(SecurityConstants.ROLE + roleId));
            // 获取资源
            dbAuthsSet.addAll(Arrays.asList(info.getPermissions()));

        }
        Collection<? extends GrantedAuthority> authorities
                = AuthorityUtils.createAuthorityList(dbAuthsSet.toArray(new String[0]));
        SysUser user = info.getSysUser();
        boolean enabled = StrUtil.equals(user.getLockFlag(), CommonConstants.STATUS_NORMAL);
        // 构造security用户

        return new DetailsUser(user.getUserId(), user.getDeptId(), user.getTenantId(),user.getAvatar(), user.getUsername(), SecurityConstants.BCRYPT + user.getPassword(), enabled,
                true, true, !CommonConstants.STATUS_LOCK.equals(user.getLockFlag()), authorities);
    }

}
